package seedpod.webapp.view.seedpodwidgets;

import java.util.ArrayList;

import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.ProtegeValueType;
import seedpod.model.rdb.MetaRdbSlot;
import seedpod.webapp.view.htmlwidget.CheckBoxInput;

/**
 * LimsWidget for
 * 
 * @author Maya Hao Li
 */
public class NSelect extends LimsWidget {
	protected ArrayList<String> values = null;
	protected String[] symbols = null;

	public NSelect() {
	// TODO Auto-generated constructor stub
	}

	public NSelect(AVPair avpair) {
		super( avpair );

		String allSymbols = getAttribute().getAllowedValues();
		if ( allSymbols != null ) symbols = allSymbols.split( MetaRdbSlot.VALUE_DELIMITER );
	}

	@Override
	public String doEdit() {
		return render();
	}

	@Override
	public String doView() {
		return render();
	}

	private boolean isChecked( String symbol ) {
		if ( values == null ) return false;
		for ( String val : values )
			if ( val.equalsIgnoreCase( symbol ) ) return true;
		return false;
	}

	@Override
	public String render() {
		try {
			validateWidget();
		} catch (InvalidWidgetException e) {
			return renderErrorComment( e.getMessage() );
		}

		String html = "";
		for ( String symbol : symbols ) {
			CheckBoxInput cb = new CheckBoxInput( getId(), symbol, isChecked( symbol ) );
			html += cb.render() + "<br>";
		}
		return html;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setData( Object data ) {
		values = new ArrayList<String>();
		if ( data == null )
			return;
		else if ( data instanceof ArrayList<?> ) {
			ArrayList arrayData = (ArrayList)data;
			for ( int i = 0; i < arrayData.size(); i++ )
				values.add( (String)arrayData.get( i ) );
		} else if ( data instanceof String )
			values.add( 0, (String)data );
		else try {
			values.add( data.toString() );
		} catch (Exception e) {
			// ignore casting error
		}
	}

	@Override
	public boolean supportsMultiValueInput() {
		return true;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		boolean isValidWidget = (getAttribute().getProtegeValueType().equals( ProtegeValueType.Symbol ) || getAttribute().getProtegeValueType().equals(
				ProtegeValueType.String )) && getAttribute().isMultiple();

		if ( !isValidWidget )
			throw new InvalidWidgetException( "This widget supports only multiple symbol of string type. " );
	}
}
